import store from '@/store';
import axios from 'axios';
import { ElMessage  } from 'element-plus'
import Router from '@/router/index';
import {serialize} from "@/utils/utils"
import {getSession} from '@/http/storage';
import qs from 'qs'

// 创建一个axios实例
const service = axios.create({
  baseURL: 'http://127.0.0.1:3000', 
  withCredentials: false, 
  timeout: 60*1000,
  //是否返回其它状态码
  validateStatus:function(status){
    return status >= 200 && status <= 500
  }
});

// 请求拦截器
service.interceptors.request.use(
  config=>{
    //模块id  智慧工地平台id为1
    config.headers.tenantId = 1
    let userInfo = getSession('userInfo')
    let token = '',userinfo = '',projectInfo = '';
    try {
      token = userInfo.token
      userinfo = userInfo
    } catch(error){console.log(error)}
    if (token) {
      config.headers['Authorization'] = `${token}`;
    }    
    // headers中配置serialize为true开启序列化
    if (config.method === 'post' && config.headers.serialize) {
      config.data = serialize(config.data)
      delete config.data.serialize
    }

    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, {arrayFormat: 'repeat'})
      }
    }
    //导出
    // if(config.type == 'download'){
    //   config.headers.responseType = 'arraybuffer'
    // }
    return config
  },
  error => {
    return Promise.reject(error);
  }
)

// 响应拦截器
service.interceptors.response.use( response=>{
    const res = response.data;
    let status = response.data.status
    //用户信息失效，重定向登录页
    if (status === 401) {
      ElMessage({
        message: '用户凭证已过期',
        type: 'error'
      })
      // 清空全部缓存 重定向到登录页
      window.localStorage.clear()
      window.sessionStorage.clear()
      Router.push({path:'/login'})
      // window.location.href = "/login";
      return
    }
    if(status === 426){
        ElMessage({
        message: '用户名不存在或密码错误',
        type: 'error'
      })
    }
    //返回错误
    console.log(status)
    if(status !== 200 && status !== 426  && status !== 1000){
      ElMessage({
        message: response.message,
        type: 'error'
      })
      return Promise.reject(new Error(response.message))
    }
    return res
  },
  error=>{
    // ElMessage({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // });
    return Promise.reject(error);
  }
)

export default service;